package com.dongge.dao;


import com.dongge.entity.User;
import com.dongge.exception.RegisterException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created by zhudong on 2016/7/18.
 */
@Repository
public class UserDao {

    @Autowired
    private SessionFactory sessionFactory;

    protected Session getSession(){
        return  sessionFactory.getCurrentSession();
    }

    public User getUserByUsername(String username){
        Session session = getSession();
        String hql = "from User u where u.username =:username";
        return (User)session.createQuery(hql).setString("username",username).uniqueResult();
    }

    public void register(String username,String password) throws RegisterException{
        User user = getUserByUsername(username);
        if(user != null){
            throw new RegisterException("用户名已经存在");
        }else {
            user = new User();
            user.setUsername(username);
            user.setPassword(password);
            Session session = getSession();
            session.save(user);
        }
    }

    public User get(long id){
        return (User)getSession().get(User.class,id);
    }

    public List<User> getUsers(){
        Session session = getSession();
        String hql = "from User";
        return session.createQuery(hql).list();
    }

    public long save(User user){
        Session session = getSession();
        return (Long)session.save(user);
    }

    public int delete(long id){
        Session session = getSession();
        String hql = "delete from User u where u.id = :id";
        return session.createQuery(hql).setLong("id",id).executeUpdate();
    }

    /**
     * 用户名绝对不能相同
     * @param user
     * @return
     */
    public int update(User user){
        Session session = getSession();
        String hql = "update User u set u.username =:username,u.password=:password"+
                "where u.id=:id";
        return session.createQuery(hql)
                .setString("username",user.getUsername())
                .setString("password",user.getPassword())
                .setLong("id",user.getId())
                .executeUpdate();
    }
}
